package com.log.compone;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;

/**
 * @Description NIO非阻塞通信
 * @Author zhaoYi
 * @Date 2024/7/16 23:40
 */
public class SelectorServerTest {

    public static void main(String[] args) throws Exception {
        System.out.println("服务器启动...");
        //1.获取通道
        ServerSocketChannel socketChannel = ServerSocketChannel.open();
        //2.设置非阻塞模式
        socketChannel.configureBlocking(false);
        //3.绑定端口
        socketChannel.bind(new InetSocketAddress(9999));
        //4.获取选择器
        Selector selector = Selector.open();
        //5.将通道注册到选择器上
        socketChannel.register(selector, SelectionKey.OP_ACCEPT);
        while (selector.select() > 0){
            //获取已就绪事件
            Iterator<SelectionKey> it = selector.selectedKeys().iterator();
            while (it.hasNext()){
                SelectionKey key = it.next();
                //判断事件类型
                if (key.isAcceptable()){
                    SocketChannel channel = socketChannel.accept();
                    channel.configureBlocking(false);
                    channel.register(selector, SelectionKey.OP_READ);
                }else if (key.isReadable()){
                    SocketChannel sChannel = (SocketChannel) key.channel();
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    int len = 0;
                    while ((len = sChannel.read(buffer)) > 0){
                        buffer.flip();
                        System.out.println(new String(buffer.array(), 0, len));
                        buffer.clear();
                    }
                }
                it.remove();
            }
        }





    }
}
